<template>
	<view class="aiWriting_box">
		<!-- <view class="creative_">
			<view class="creative_s">
				{{writing}}
			</view>
		</view> -->
		<view class="creative_results">
		<!-- 	<view class="creative-s" @click="goTextDetection">
				历史记录
			</view> -->
			<view class="creative_resultss">
				<view class="title">
					创作结果
				</view>
				<view style="margin-left: 220rpx;color: #9e9e9e;font-size: 25rpx;margin-bottom: 20rpx;">
					(该结果由AI生成仅供参考)
				</view>
				<view class="results_textarea">
					<view class="results-content">
						{{creativeResults}}
					</view>
				</view>
				<view class="right-s" v-if="Liupaer">
					结果字数{{creativeResults.length}}
				</view>
			</view>
			<view style="display: flex;" v-if="Liupaer">
				<view class="creative_results_btn" @click="copyResults">
				<!-- 	<image class="btes" src="../../static/icon/5.png" style="width: 50rpx;height: 50rpx;"></image> -->
					<view class="bts">复制结果</view>
				</view>
				<!-- <view class="creative_results_btn" style="background: #5490ff;" @click="posters"> -->
				<view class="creative_results_btn" style="background: #5490ff;">
				<!-- 	<image class="btes" src="../../static/icon/2x.png" style="width: 50rpx;height: 50rpx;"></image> -->
					<view class="bts" @click="historical">保存结果</view>
					<!-- <button class="dialog-shadow-bottom-item"
						style="border:none;border: none;width: 220rpx;" :plain="true"
						@click="historical">
						<view class="dialog-shadow-bottom-item-text"
							style="color: white;font-size: 30rpx;">保存结果</view>
					</button> -->
				</view>
			</view>
		</view>
		<view v-if="showCanvas" class="canvasView" :style="{'z-index':showCanvas?'300':'0'}">
			<canvas :style="{'width':canvasWidth+'px', 'height':canvasHeight+'px'}" canvas-id="myCanvas" />
		</view>
		<uni-popup ref="popup" type="center">
			<view class="">
				<canvas canvas-id="gameCanvas" style="width:632rpx; height:1149rpx;"></canvas>
			</view>
		</uni-popup>

		<!-- 选择分享的方式 -->
		<u-popup closeable :show="showMore" @close="close" :round="10" :safeAreaInsetBottom="false">
			<view class="morebar">
				<view class="moretext">选择分享方式</view>
			</view>
			<view class="more_box">
				<!-- #ifdef MP-WEIXIN -->
				<view class="editView" @click="toPopupDialogForShare()">
					<image class="editIcon" src="../../static/markMoney/tp.png"></image>
					<text class="againedit">海报分享</text>
				</view>
				<!-- #endif -->

				<button plain="true" open-type="share" style="border:none" class="dialog-shadow-bottom-item">
					<view class="dialog-shadow-bottom-item-img">
						<image mode="scaleToFill" style="width: 100%;height: 100%" src="../../static/markMoney/wx.png">
						</image>
					</view>
					<view class="dialog-shadow-bottom-item-text">微信好友/群</view>
				</button>

			</view>
		</u-popup>
	</view>
</template>

<script>
	import * as TextEncoding from 'text-encoding-shim';
	import cryptoJs from '@/utils/encryptDES.js'
	import {
		myShowLoading,
		myHideLoading,
	} from "../../utils/showToast.js";
	import {
		isLogin,
		vipType
	} from '@/business/login.js';
	import {
		wxTextDetection
	} from "../../utils/textCheck.js";
	import {
		wycUrl,
		wycUrlApi,
		black
	} from '@/api/assemb.js'
	import store from '../../store/idnex.js'
	import config from "../../uni_modules/uview-ui/libs/config/config.js";
	import {
		apiMixUrlApi
	} from "../../api/assemb";

	function hasDuplicateSubstring(str, substring) {
		const regex = new RegExp(substring, 'g'); // 创建一个全局搜索的正则表达式  
		const matches = str.match(regex); // 使用match方法查找所有匹配项  
		return matches && matches.length > 1; // 如果有匹配项且数量大于1，则返回true，否则返回false  
	}
	var diff = require('diff');
	let app = getApp();
	export default {
		data() {
			return {
				showMore: false, //分享结果的弹窗
				relativeScale: '',
				canvasPath: '',
				imageWidth: 316,
				imageHeight: 575,
				creatImg: '',
				erCode: '',
				ercodeImg: '',
				creativeResults: '',
				writing: '',
				lenth: true,
				showCanvas: false,
				canvasHeight: 500,
				canvasWidth: 300,
				isVip: false,
				content: '您还不是会员,此功能需开通会员才可使用。',
				compareResults: [],
				vipShow: false,
				frequency: uni.getStorageSync('frequency'),
				aiLevel: 1,
				originality: 0,
				width: 0,
				arrIndex: [],
				widthIndex: 0,
				schedule: 0,
				scheduleShow: false,
				time: null,
				pos: '',
				Liupaer: false,
				ptt:'',
				queue:'',
				proes:false
			};
		},
		onShow() {
			console.log(getApp().globalData.Liupaer)
			// this.isVip = true;
			// this.posters()
			this.isVip = uni.getStorageSync('vipType').vipStatus == 1 ? true : false;
		},
		onLoad(options) {
			console.log(options.creativeResults)
			this.writing = options.writing
			this.aaa()

			var time = new Date()
			let baseinfo = uni.getStorageSync('baseinfo');
			console.log('baseinfo', baseinfo)
			this.userid = baseinfo.userid

		},
		methods: {
			//非会员扣次数
			feacter(){
				if (!this.isVip) {
					let param = {
						consumecoins: 1,
						descinfo: '一键创作消耗',
						consumetype: 1,
					}
					apiMixUrlApi(param, '1043', "ConsumeCoins").then(result => {
						console.log(result, '1043返回值');
						uni.setStorageSync('frequency', result.coins)
					});
				}
			},
			historical() {
				let today = new Date();
				let month = today.getMonth() + 1;
				let currentDate = today.getFullYear() + "-" + month + "-" + today.getDate();
				let tooles = {
					title: this.creativeResults,
					time: currentDate
				}
				if (uni.getStorageSync('content')) {
					if (uni.getStorageSync('content').length < 20) {
						let content = uni.getStorageSync('content')
						content.push(tooles)
						uni.setStorageSync('content', content);
					} else if (uni.getStorageSync('content').length = 20) {
						let content = uni.getStorageSync('content').slice(1)
						content.push(tooles)
						uni.setStorageSync('content', content);
					}

				} else {
					console.log('111111111')
					let content = []
					content.push(tooles)
					uni.setStorageSync('content', content);
				}
				uni.showToast({
					title: '保存成功'
				})
			},
			// fn(){
			// 	return this.Liupaer = getApp().globalData.Liupaer
			// },
			aaa() {
				let that = this
				uni.showLoading({
					title: '创作中'
				})
				// const param = {
				// 	content: this.writing
				// }
				// console.log(param, '11')
				// const requestTask = black(param)
				const requestTask = wx.request({
					url: 'https://biz.teltranslator.com/chat/api/c=1012&v=4&a=wxzy', // 服务端接口地址
					data: cryptoJs.encrypt(JSON.stringify({
						cmd: "bdStream",
						base: wx.getStorageSync("baseinfo"),
						param: {
							content: that.writing
						},
					}), 1012),
					method: 'POST',
					enableChunked: true,
					header: {
						//'content-type': 'application/x-www-form-urlencoded',
						Accept: 'text/event-stream'
					},
					success: (response) => {
						that.feacter()
						// uni.hideLoading()
						// for (let i = 0; i < this.ptt.length; i++) {
						// 	setTimeout(() => {
						// 		this.creativeResults += this.ptt[i];
						// 	}, i *20 );
						// }
						// 开启enableChunked后，成功的回调一般用不到，因为响应数据不在这里返回
						// console.log(response, '成功结束',getApp().globalData.Liupaer);
						if (response.errMsg == "request:ok") {
							console.log(that.creativeResults.length)
							
							that.Liupaer = true
							// console.log(getApp().globalData.Liupaer)
						}
					},
					fail: (err) => {
						// 开启enableChunked后，成功的回调一般用不到，因为响应数据不在这里返回
						console.log(err, '失败');
						uni.showToast({
							title: '出错了请重试',
							icon: 'none',
							duration: 2000
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 2000);
					}
				});
				requestTask.onChunkReceived((chunk) => {
					uni.hideLoading()
					const arrayBuffer = chunk.data;
					const uint8Array = new Uint8Array(arrayBuffer);
					const str = new TextEncoding.TextDecoder('utf-8').decode(uint8Array);
					that.pos = str.replace(/data:/g, '');
					if (hasDuplicateSubstring(that.pos, 'data')) {
						const pt = that.pos.replace(/\r?\n/g, '')
						const pos = pt.replace(/"code":200,"message":"SUCCESS","data":/g, '');
						const ps = pos.replace(/[{}""]/g, '') + '"}';
						const rs = '{"code":200,"message":"SUCCESS","data":"'
						that.pos = rs + ps
						console.log(JSON.parse(that.pos), '处理重复的')
					}
					const po = JSON.parse(that.pos)
					console.log(po)
					if (po.code == 200) {
						 // // that.queue.push(po.data);  
						 // that.queue+=po.data
						 // that.proes = true
						 // console.log(that.queue,'--')
							for (let i = 0; i < po.data.length; i++) {
								setTimeout(() => {
									this.creativeResults += po.data[i];
								}, i * 2);
							}
							
							
                        // this.ptt += po.data
					} else {
						this.creativeResults = ''
						uni.showToast({
							title: '出错了请重试',
							icon: 'none',
							duration: 2000
						})
						setTimeout(() => {
							uni.navigateBack()
						}, 2000);
					}
					// setTimeout(() => {
					// 	if(that.proes = true){
					// 		for (let i = 0; i <  that.queue.length; i++) {
					// 			setTimeout(() => {
					// 				this.creativeResults +=  that.queue[i];
					// 			}, i * 10);
					// 		}
					// 	}
					// }, 2000);
				
					// var a1 = str.replace(reg1,"");
				});
			},
			goTextDetection(writing) {
				uni.navigateTo({
					url: '../save/save'
				})

			},
			// 打开会员
			openVip() {
				if (uni.getStorageSync('OS') !== 'ios') {
					uni.navigateTo({
						url: '/pages/paymentCenter/paymentCenter'
					});
				} else {
					if (getApp().globalData.iosPay == 0) {
						uni.showModal({
							title: '提示',
							content: '由于相关规范，IOS功能暂不可用',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {
									console.log('用户点击确定');
								} else if (res.cancel) {
									console.log('用户点击取消');
								}
							}
						});
					} else if (getApp().globalData.iosPay == 1) {
						uni.navigateTo({
							url: '/pages/goods/goods'
						});
					}
				}
			},
			// // 非会员截取
			// interCept(str) {
			// 	return str.slice(0, 200);
			// },
			// // 非会员截取
			// interCepts(str) {
			// 	if(str.length >= 400){
			// 		return str.slice(200, 400) + '...';
			// 	} else {
			// 		return str.slice(200, str.length - 200) + '...';
			// 	}
			// },
			WaddAudio() {
				this.showMore = true;
			},
			//上传选择关闭
			close() {
				this.showMore = false;
			},


			//复制结果
			copyResults() {
				if (this.isVip) {
					uni.setClipboardData({
						data: this.creativeResults,
						showToast: true
					});
				} else {
					uni.showToast({
						title: '请开通会员后复制',
						icon: 'none'
					})
				}
			},
			//分享结果
			onShareAppMessage(res) {
				const that = this
				this.showMore = false;
				// if (res.from === 'button') { // 来自页面内分享按钮
				// 	console.log(res.target, 'res.target')
				// }
				return {
					title: 'AI写作神器，一键改写变原创。',
					path: "pages/home/home?userid=" + that.userid,
					imageUrl: "https://iflytts.oss-cn-qingdao.aliyuncs.com/wxapp/xze/6.png",
					success: function(res) {
						console.log(
							"--------------转发成功--------------------",
							res,
							that.userid
						);
					}
				}
			},

			delWriting() {
				this.writing = ''
			},
		}
	}
</script>

<style lang="scss">
	/deep/.u-textarea--disabled {
		background-color: #fff !important;
	}

	/deep/.u-textarea {
		padding-top: 0 !important;
		padding-bottom: 0 !important;
	}

	/deep/.u-button {
		border-radius: 12rpx !important;
	}

	/deep/.u-icon__icon {
		margin-right: 8rpx !important;
	}

	/deep/.u-checkbox__icon-wrap {
		width: 26rpx !important;
		height: 26rpx !important;
		margin-left: 57rpx;
	}

	/deep/.u-textarea .u-textarea__field {
		line-height: 25px;
	}

	.right-s {
		width: 150rpx;
		margin-left: 550rpx;
		font-size: 20rpx;
		color: #333333;
		position: absolute;
		bottom: 2px;
	}

	.dialog-shadow-bottom-item {
		width: 33%;
		height: 100%;
		display: flex;
		margin-left: 120rpx;
		justify-content: center;
		align-items: center;
		flex-direction: column;

		.dialog-shadow-bottom-item-img {
			width: 109rpx;
			height: 109rpx;
		}

		.dialog-shadow-bottom-item-text {
			width: 100%;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 22rpx;
		}
	}

	.morebar {
		margin-top: 30rpx;
		display: flex;
		flex-direction: column;
		background-color: white;
		height: 70rpx;
		border-bottom: 1rpx solid #f6f5ec;

		.moretext {
			width: 100%;
			text-align: center;
			color: #3e3e3e;
		}
	}

	.more_box {
		display: flex;
		padding: 60rpx 0;
		margin-left: 110rpx;
		justify-content: space-around;

		.editView {
			display: flex;
			flex-direction: column;
			align-items: center;
			width: 33%;
		}

		.editIcon {
			width: 109rpx;
			height: 109rpx;
		}

		.againedit {
			margin-top: 10rpx;
			font-size: 22rpx;
			color: #333333;
		}
	}

	.textarea-placeholder {
		line-height: 30rpx;
	}

	.title {
		line-height: 80rpx;
		width: 100%;
		display: flex;
		justify-content: center;
		font-size: 34rpx;
		font-family: PingFang SC;
		color: #5490FF;
	}

	.creative_results {
		padding-bottom: 30rpx;
		margin-top: 20rpx;
		width: 696rpx;
		border-radius: 18rpx;
		box-sizing: border-box;
		position: relative;

		.creative-s {
			position: absolute;
			right: 40rpx;
			font-family: PingFang SC;
			color: #999999;
			top: 38rpx;
			font-size: 25rpx;
		}

		.creative_resultss {
			min-height: 500rpx;
			background: #FFFFFF;
			padding-bottom: 20rpx;
            position: relative;
			.results_textarea {
				padding: 0 20rpx 0rpx 20rpx;
			}

			.results-content {
				width: 100%;
				color: #606266;
				font-size: 15px;
				display: inline-block;
				white-space: pre-wrap;
				word-wrap: break-word;
				height: auto;
				position: relative;

				.results-content-muchtext {
					opacity: 0.08;
				}

				.mask_tip {
					position: absolute;
					width: 100%;
					display: flex;
					justify-content: center;
					align-items: center;
					bottom: 60rpx;

					.vip_tip {
						width: 376rpx;
						height: 107rpx;
					}
				}
			}
		}

		.creative_results_btn {
			margin: auto;
			margin-top: 30rpx;
			width: 300rpx;
			display: flex;
			height: 85rpx;
			background: #1EB930;
			border-radius: 14rpx;
			justify-content: center;
			align-items: center;

			.bts {
				color: white;
				font-size: 30rpx;
			}

			.btes {
				color: white;
			}
		}

	}

	.originality {
		margin-top: 64rpx;

		ul {
			display: flex;

			li {
				display: flex;
				width: 193rpx;
				height: 43rpx;
				font-size: 18rpx;

				.left {
					width: 102rpx;
					height: 43rpx;
					color: #FFFFFF;
					text-align: center;
					line-height: 43rpx;
					border-radius: 6rpx 0rpx 0rpx 6rpx;
				}

				.right {
					width: 92rpx;
					height: 43rpx;
					color: #333333;
					text-align: center;
					line-height: 43rpx;
					background-color: #fff;
					border-radius: 0rpx 6rpx 6rpx 0rpx;
				}
			}
		}
	}

	.button {
		margin-top: 62rpx;
		width: 100%;
		display: flex;
		justify-content: space-between;

		.button_left {
			width: 47%;
		}

		.button_right {
			position: relative;
			width: 100%;

			.right_other {
				display: flex;
				align-items: center;
				position: absolute;
				top: -21rpx;
				right: 0;
				width: 154rpx;
				height: 42rpx;
				background: #FF6600;
				border-radius: 21rpx 0rpx 0rpx 21rpx;

				text {
					line-height: 42rpx;
					margin-left: 18rpx;
					font-size: 18rpx;
					font-family: PingFang SC;
					color: #FFFFFF;
				}
			}
		}
	}

	.textarea {
		height: 722rpx;
		padding-top: 15rpx;
	}

	.text {
		font-size: 19rpx;
		font-family: PingFang SC;
		color: #999999;
	}

	.aiWriting_box {
		padding: 0 27rpx;

		.content {
			width: 696rpx;
			height: 822rpx;
			border-radius: 18rpx;
			background-color: #fff;
			margin-top: 20rpx;
		}

		.tools {
			height: 80rpx;
			padding: 0 27rpx;
			display: flex;
			justify-content: space-between;

			.tools_left {
				display: flex;
				justify-content: space-between;

				.left {
					display: flex;
					justify-content: space-between;
					align-items: center;
				}

				.right {
					margin-left: 40rpx;
					display: flex;
					justify-content: space-between;
					align-items: center;
				}
			}

			.tools_right {
				display: flex;
				align-items: center;
			}
		}
	}
</style>
<style>
	page {
		background-color: #f4f4f4;

	}

	.schedule-page {
		width: 100%;
		height: 100vh;
		position: fixed;
		background-color: rgba(128, 126, 126, 0.8);
		top: 0px;
		left: 0px;
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 200;
	}

	.schedule-box {
		width: 82%;
		background-color: #fff;
		border-radius: 15rpx;

	}

	.schedule-text {
		text-align: center;
		line-height: 120rpx;
	}

	.schedule {
		width: 100%;
		height: 20rpx;
		margin: 20rpx 0rpx;
	}

	.schedule-number {
		width: 100%;
		height: 100rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #2979ff;
	}

	.lineBox {
		width: 90%;
		display: flex;
		justify-content: space-around;
		margin: 0px auto;
		height: 12rpx;
		border-radius: 40rpx;
		overflow: hidden;
	}

	.lineAnimation {
		height: 100%;
		background-color: #bbb9b9;
	}

	.lineAnimation-children {
		height: 100%;
		transition: all 0.5s;
		background-color: #2979ff;
	}

	.canvasView {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		background: yellow;
	}

	.creative_ {
		width: 700rpx;
		height: auto;
		background: white;
		color: #999999;
		height: 250rpx;
		border-radius: 15rpx;
	}

	.creative_s {
		-webkit-line-clamp: 2;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		overflow: hidden;
		text-overflow: ellipsis;
		padding: 20rpx 20rpx 0rpx 20rpx;
		font-size: 28rpx;
	}
</style>